package ru.alperez.gpsdub.adapter;

import java.util.List;
import java.util.Map;

import ru.alperez.gpsdub.R;
import ru.alperez.model.GpsPoint;
import ru.alperez.model.ResultSavePoint.PointSaveConflictType;
import ru.alperez.util.Converter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ConflictListAdapter extends ArrayAdapter<Map<String, Object>>{
	private LayoutInflater inflater;
	
	public ConflictListAdapter(Context context, List<Map<String, Object>> conflicts) {
		super(context, R.layout.conflict_list_item, conflicts);
		inflater = LayoutInflater.from(context);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ConflictItemHolder holder;
		Map<String, Object> conflict = getItem(position);
		PointSaveConflictType conflictType = (PointSaveConflictType) conflict.get("confl_type");
		GpsPoint  conflictPoint = (GpsPoint) conflict.get("point");
		if (row == null) {
			row = inflater.inflate(R.layout.conflict_list_item, parent, false);
			holder = new ConflictItemHolder(row, conflictPoint);
			row.setTag(holder);
		}
		else {
			holder = (ConflictItemHolder) row.getTag();
		}
		
		if (conflictType != null) {
			switch (conflictType) {
			case CONFLICT_NAME:
				holder.getConflictType().setText("Name");
				break;
			case CONFLICT_LOCATION:
				holder.getConflictType().setText("Location");
				break;
			default:
				holder.getConflictType().setText("UNKNOWN");
			}
		} else {
			holder.getConflictType().setText("null");
		}
		try {
			holder.getName().setText(conflictPoint.getName());
			holder.getDate().setText(Converter.gpsDateTimeFromLocation(conflictPoint.getLocation()));
		} catch (NullPointerException e) {
			holder.getName().setText("null");
			holder.getDate().setText("null");
		}
		return row;
	}
	
	
	
	
	
	public class ConflictItemHolder {
		private View base;
		private TextView name;
		private TextView date;
		private TextView conflictType;
		private GpsPoint gpsPoint;
		
		public ConflictItemHolder(View base, GpsPoint gpsPoint) {
			this.base = base;
			this.gpsPoint = gpsPoint;
		}
		
		public TextView getName() {
			if (name == null) {
				name = (TextView) base.findViewById(R.id.conflict_item_name);
			}
			return name;
		}
		
		public TextView getDate() {
			if (date == null) {
				date = (TextView) base.findViewById(R.id.conflict_item_date);
			}
			return date;
		}
		
		public TextView getConflictType() {
			if (conflictType == null) {
				conflictType = (TextView) base.findViewById(R.id.conflict_item_conflict);
			}
			return conflictType;
		}
		
		public GpsPoint getGpsPoint() {
			return gpsPoint;
		}
	}
}
